import threading
import pgzrun
import time as tm
import tkinter as tk
from tkinter import filedialog
import json as js
import random

ROWS = 100
COLS = 100
world = []
CELL_SIZE = 7

def TK():
	global ROWS
	global COLS
	global world
	
	top = tk.Tk()
	
	frames = []
	for i in range(3):
		frames.append(tk.Frame(top))
	for i in frames:
		i.pack()
	
	entries = []
	tk.Label(frames[0], text='rows:').pack(side='left')
	entries.append(tk.Entry(frames[0]))
	entries[0].pack(side='left')
	tk.Label(frames[1], text='cols:').pack(side='left')
	entries.append(tk.Entry(frames[1]))
	entries[1].pack(side='left')
	
	def Load():
		rows = entries[0].get()
		cols = entries[1].get()
	
	def Save():
		with open('world.json', 'w') as f:
			js.dump(
				{
					'rows' : ROWS,
					'cols' : COLS,
					'world' : world
				},
				f
			)
	
	def Clean():
		world = []
	
	def Open():
		top.filename = filedialog.askopenfilename(
			initialdir = "./",
			title = "Select file"
		)
		with open(top.filename, 'r') as f:
			t = js.load(f)
		Clean()
		for i in t:
			x=i[0]
			y=i[1]
			world[int(x)][int(y)] = 1
	
	buttons = []
	buttons.append(tk.Button(frames[2], text='load', command=Load))
	buttons.append(tk.Button(frames[2], text='save', command=Save))
	buttons.append(tk.Button(frames[2], text='clean', command=Clean))
	buttons.append(tk.Button(frames[2], text='open', command=Open))
	for i in buttons:
		i.pack(side='left')
	
	top.mainloop(0)


HEIGHT = (ROWS * CELL_SIZE)
WIDTH  = (COLS * CELL_SIZE + 90)

BACK_COLOR = (0, 0, 50)

def GenCellColor():
	return [random.randint(0, 50), random.randint(175, 250), random.randint(50, 100)]

def init_map(rows, cols):
	return [[[0, BACK_COLOR] for c in range(cols)] for r in range(rows)]

def save():
	files=os.listdir(".")
	x=0
	name=""
	while True:
		name="LifeGameMap"+str(x)+".json"
		if name not in files:
			break
		x+=1
	os.mknod(name)
	f=open(name,'w')
	f.write('{"size":['+str(ROWS)+','+str(COLS)+','+str(CELL_SIZE)+"],\n")
	f.write('"map":[\n')
	n=[]
	for i in range(len(world)):
		for j in range(len(world[i])):
			if not world[i][j][0]:
				continue
			o=("["+str(i)+','+str(j)+']')
			n.append(o)
	for i in range(len(n)):
		f.write(n[i])
		if i!=len(n)-1:
			f.write(',')
	f.write(']}')
		
	f.close()

world = init_map(ROWS, COLS)
on=[0,0]

def get_cells(world):
	x=0
	for i in range(ROWS):
		for j in range(COLS):
			x+=world[i][j][0]
	return x

def on_key_down(key):
	global world
	if key==keys.DELETE:
		world=init_map(ROWS,COLS)
	if key==keys.END:
		save()

def on_mouse_down(pos, button):
	global world
	x=pos[1]//CELL_SIZE
	y=pos[0]//CELL_SIZE
	if y>=COLS:
		return
#    print(x,y)
	if button == mouse.LEFT:
		world[x][y]=[1, GenCellColor()]
	else:
		world[x][y]=[0, GenCellColor()]

def on_mouse_move(pos):
	global on
	x=pos[1]//CELL_SIZE
	y=pos[0]//CELL_SIZE
	if y>COLS:
		return
	on=[x,y]

def draw_cell(w, r, c):
	cx = CELL_SIZE * c
	cy = CELL_SIZE * r
	cell_rect = Rect((cx, cy), (CELL_SIZE, CELL_SIZE))
	screen.draw.filled_rect(cell_rect, tuple(w[r][c][1]))

def draw_line(w, r, c):
	cx = CELL_SIZE * c
	cy = CELL_SIZE * r
	line_rect = Rect((cx, cy), (CELL_SIZE+1, CELL_SIZE+1))
	screen.draw.rect(line_rect, (150,150,150))

def update():
	pass

def draw():
	screen.fill(tuple(BACK_COLOR))
	for r in range(ROWS):
		for c in range(COLS):
			if world[r][c][0]:
				draw_cell(world, r, c)
	for i in range(0,WIDTH-89,CELL_SIZE):
		screen.draw.line((i,0),(i,HEIGHT),(150,150,150))
	for i in range(0,HEIGHT,CELL_SIZE):
		screen.draw.line((0,i),(WIDTH-90,i),(150,150,150))

TK_ = threading.Thread(target=TK)
TK_.start()

pgzrun.go()
